﻿using EpubFactory.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace EpubFactory.Lib99.Service
{
    public class BiqugeReceipe : Receipe
    {
        Regex contentRegex = new Regex(@"<div id=""content"">([\s\S]+)</div>", RegexOptions.IgnoreCase | RegexOptions.Compiled);
        public override IEnumerable<Uri> SourceUriList
        {
            get { return new string[] { "http://www.biquge.lu" }.Select(g => new Uri(g)); }
        }

        public override string Name
        {
            get { return "biquge"; }
        }
        public override Encoding SiteEncoding
        {
            get
            {
                return Encoding.GetEncoding("gbk");
            }
        }

        public override Book GetBook()
        {
            var book = GetEmptyBook();

            book.Host = ExtractHost(entrypoint);
            var html = GetCachedContent(this.entrypoint);
            var doc = new HtmlAgilityPack.HtmlDocument();
            using (var reader = new StringReader(html))
            {
                doc.Load(reader);
            }
            //doc.LoadHtml(html);
            var metaList = doc.DocumentNode.SelectNodes("//meta");

            foreach (var meta in metaList.Where(g => g.HasAttributes && g.Attributes.Contains("property")))
            {
                var property = meta.Attributes["property"];
                switch (property.Value)
                {
                    case "og:image":
                        book.CoverUrl = meta.GetAttributeValue("content", string.Empty);
                        break;
                    case "og:novel:category":
                        book.Subject = meta.GetAttributeValue("content", string.Empty);
                        break;
                    case "og:novel:author":
                        book.Authors.Add(meta.GetAttributeValue("content", string.Empty));
                        break;
                    case "og:novel:book_name":
                        book.Title = meta.GetAttributeValue("content", string.Empty);
                        break;
                    case "og:description":
                        book.Summary = meta.GetAttributeValue("content", string.Empty);
                        break;
                }
            }

            ParseChapterLinks(book, doc);
            book.EPubId = ExtractBookId(entrypoint);
            RemoveDuplicateChapters(book);
            return book;

        }
        private void RemoveDuplicateChapters(Book book)
        {
            int i = 0;
            foreach (var chapter in book.Chapters)
            {
                if (!book.Chapters.Skip(i + 1).Any(d => d.Title == chapter.Title))
                {
                    break;
                }
                i++;
            }
            book.Chapters = book.Chapters.Skip(i).ToList();
        }
        private void ParseChapterLinks(Book book, HtmlAgilityPack.HtmlDocument doc)
        {
            int sortNo = 1;
            var linkList = doc.DocumentNode.SelectNodes("//dd/a");
            foreach (var link in linkList)
            {
                var chapter = new Chapter()
                {
                    Book = book,
                    Href = book.Host + link.GetAttributeValue("href", string.Empty),
                    SortOrder = sortNo++,
                    Title = link.InnerText
                };
                book.Chapters.Add(chapter);
            }
        }
        public override void CleanChapter(Chapter chapter)
        {
            base.CleanChapter(chapter);
            var contentHtml = contentRegex.Match(chapter.SourceContent).Groups[1].Value;
            chapter.Content = contentHtml.Replace("&nbsp;", "").Replace("<br />", Environment.NewLine);
        }
        public override string ExtractBookId(string url)
        {
            var a = url.LastIndexOf('/');
            if (a != url.Length - 1)
            {
                return url.Substring(a + 1);
            }
            var b = url.Substring(0, a);
            var c = b.LastIndexOf('/');
            return b.Substring(c + 1);
        }
    }
}
